import React, { useEffect, useState } from 'react'
import { gettable } from "../../api/axios";
import Gao from "../../utils/Gao";
import { useAppDispatch, useAppSelector } from "../../utils/Hook";
import { setlist, del, add_table, edit_table, alldel_table } from "../../store/module/table";
import { Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import { Flex, Progress } from 'antd';
import type { PopconfirmProps } from 'antd';
import { Button, message, Popconfirm } from 'antd';
import { Modal } from 'antd';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';
interface Props {

}
interface DataType {
    key: string;
    name: string;
    age: number;
    sex: string,
    icon: string,
    price: string,
    pro: number
}

type FieldType = {
    key?: string;
    icon?: string;
    name?: string;
    age?: number;
    price?: string;
    pro?: number;
    sex?: string

};
const Index = (props: Props) => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [title, settitle] = useState('')
    const dispatch = useAppDispatch()
    //表单内容的form
    const [form] = Form.useForm();
    //
    const [isModalOpen, setIsModalOpen] = useState(false);
    //
    const table = useAppSelector(state => state.table.tablelist)

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //得到修改的key值
    const [key, setKey] = useState('')
    //提交表单
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        if (title === '新增信息') {
            values.key = new Date().getTime().toString()
            values.icon = 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg'
            console.log('Success:', values);
            dispatch(add_table(values))
        }
        else {
            values.key = key
            dispatch(edit_table(values))

        }
        setIsModalOpen(false);

    };
    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    //新增
    const add = () => {
        //显示弹框
        setIsModalOpen(true);
        //设置标题
        settitle('新增信息')
        //表单内容消失
        form.resetFields();

    }
    //修改
    const edit = (values: DataType) => {
        //显示弹框
        setIsModalOpen(true);
        //设置标题
        settitle('修改信息')
        //内容回显
        form.setFieldsValue(values);
        //得到key值
        setKey(values.key)
    }
    //删除
    const confirm = (key: string) => {
        // console.log(key);
        message.success('确认删除');
        dispatch(del(key))
    };

    const cancel = (key: string) => {
        console.log(key);
        message.error('取消删除');
    };

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '编号',
            dataIndex: 'key',
            key: 'key',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '头像',
            dataIndex: 'icon',
            key: 'icon',
            render: (text) => <img src={text} style={{ width: '80px', height: '80px' }}></img>,
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            filters: [
                {
                    text: '男',
                    value: '男',
                },
                {
                    text: '女',
                    value: '女',
                },
            ],
            onFilter: (value, record) => record.sex.indexOf(value as string) === 0,
        },
        {
            title: '价钱',
            dataIndex: 'price',
            key: 'price',
        },
        {
            title: '进度条',
            dataIndex: 'pro',
            key: 'pro',
            render: (text) => <Progress type="circle" percent={text} />,
            sorter: (a, b) => a.pro - b.pro,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a>查看 {record.name}</a>
                    <Popconfirm
                        title="确认删除？"
                        description="Are you sure to delete this task?"
                        onConfirm={() => confirm(record.key)}
                        onCancel={() => cancel(record.key)}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button danger>删除</Button>
                    </Popconfirm>
                    <Button danger onClick={() => edit(record)}>修改</Button>
                </Space>
            ),
        },
    ];


    useEffect(() => {
        (
            async () => {
                let res = await gettable()
                if (res.status === 200) {
                    dispatch(setlist(res.data))
                }
            }
        )()
    }, [])
    // const [inp, setInp] = useState('')
    // const [table2, setTable2] = useState([])
    // const ss = () => {
    //     if (inp === '') {
    //         setTable2(table)
    //     }
    //     else {
    //         let newtable = table.filter((item: DataType, index) => {
    //             return item.name.includes(inp)
    //         })
    //         setTable2(newtable)
    //     }
    // }

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);

    };


    const alldel = () => {
        dispatch(alldel_table(selectedRowKeys))
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    return (
        <div>
            <input type="text" placeholder='请输入搜素内容' /><Button type="primary">搜索</Button><br></br>
            <Button type="primary" onClick={add}>
                新增
            </Button>
            <Button onClick={alldel}>批量删除</Button>
            <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="姓名"
                        name="name"
                        rules={[{ required: true, message: 'Please input your 姓名!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<FieldType>
                        label="年龄"
                        name="age"
                        rules={[{ required: true, message: 'Please input your 年龄!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="性别"
                        name="sex"
                        rules={[{ required: true, message: 'Please input your 性别!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<FieldType>
                        label="价钱"
                        name="price"
                        rules={[{ required: true, message: 'Please input your 性别!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item<FieldType>
                        label="进度条"
                        name="pro"
                        rules={[{ required: true, message: 'Please input your 进度条!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            Submit
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table columns={columns} dataSource={table} rowSelection={rowSelection} />
        </div>
    )
}

export default Gao(Index)
